package com.j1ay.forum.filter;

import com.alibaba.fastjson.JSON;
import com.j1ay.forum.model.pojo.JwtUser;
import com.j1ay.forum.model.pojo.po.Permission;
import com.j1ay.forum.model.pojo.po.User;
import com.j1ay.forum.model.pojo.vo.ErrorCode;
import com.j1ay.forum.service.UserService;
import com.j1ay.forum.service.impl.UserDetailsServiceImpl;
import com.j1ay.forum.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Author J1ay
 * @Date 2021/12/19 17:36
 * @Description 自定义的Token过滤器,登录后，获取到token后，检验token
 */


public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestUrl = httpServletRequest.getRequestURI();

        String authToken = httpServletRequest.getHeader(JwtTokenUtil.TOKEN_HEADER);

        System.out.println("AuthToken==>" + authToken);
        // 先对获得的 authToken进行判空, 若为空，直接放行
        if (StringUtils.isBlank(authToken) || !authToken.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        String token = authToken.replace(JwtTokenUtil.TOKEN_PREFIX, "");
        // 若不为空，则从redis中比对token
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        System.out.println(userJson);
        if (StringUtils.isBlank(userJson)) {
            // 此时redis里面没有token, 说明token已经过期了
            throw new ServletException(ErrorCode.TOKEN_FAILED.getMsg());
        }
        else {
            JwtUser jwtUser = JSON.parseObject(userJson, JwtUser.class);
            Long userId = jwtUser.getId();
            System.out.println("进入自定义过滤器");
            System.out.println("自定义过滤器获得用户id为   " + userId);
            // 进行token验证
            if (jwtTokenUtil.validateToken(authToken, jwtUser)) {
                // 邮箱、用户名、昵称多方登录
                //UserDetails userDetails = this.userDetailsService.loadUserByUsername(jwtUser.getUsername());
                JwtUser jwtUser1 = userService.findUserByUseId(userId, authToken);
                //System.out.println("userDetails ===> " + userDetails.getAuthorities());
                System.out.println("jwtUser1 ===> " + jwtUser1.getAuthorities());
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(jwtUser1, null, jwtUser1.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));

                //将authentication放入SecurityContextHolder中
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            else {
                throw new ServletException(ErrorCode.TOKEN_FAILED.getMsg());
            }

            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }

        //String username = jwtTokenUtil.getUsernameFromToken(authToken);
//        // 验证token是否是有效的token
//        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
//            //token中 username不为空，并且Context中的认证为空，进行token验证
//            // 从数据库得到带有密码的完整user信息
//            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

//            System.out.println("============>" + userDetails);


//        }

    }

}
